<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '修改编录号' : '新建编录号'"
    :toolbar-attrs="{ buttons: ['back', { edit: isDisabled, save: isEnabled }, 'cancel'] }"
    :toolbar-listeners="{ save: persist }">
    <template #toolbar-right> </template>
    <FormHolder ref="form" label-width="110px" :disabled="isDisabled" :model="entity">
      <FormItemGroup block-title="基本信息">
        <FormTreeSelect
          :value="entity.parentId"
          label="父级编录号"
          :options="options"
          prop="parentId"
          @input="onInputParent">
          <template #value-label="{ node }">
            {{ node.raw.fullName }}
          </template>
        </FormTreeSelect>
        <FormInput v-model="entity.name" prop="name" label="编录号" required max-length="255" />
        <FormInput :value="fullName" prop="fullName" readonly label="编录号全称" max-length="500" />
      </FormItemGroup>
    </FormHolder>
  </FormView>
</template>

<script>
  import { create, getTree, load, save, update } from './api'
  import form from '@/vue/mixin/form'
  import { findTreeChildren } from '@web-utils/core'

  export default {
    name: 'BookCategoryForm',
    relativeViewId: 'BookCategoryView',
    mixins: [form],
    data() {
      return {
        entity: {
          id: null,
          unid: null,
          createTime: null,
          createBy: null,
          createId: null,
          deptId: null,
          deptFullName: null,
          updateTime: null,
          updateId: null,
          updateBy: null,
          tenantId: null,
          delFlag: null,
          parentId: null,
          name: null,
          fullName: null
        },
        options: []
      }
    },
    computed: {
      fullName() {
        const nodes = findTreeChildren(this.options, node => node.id === this.entity.parentId)
        if (nodes.length) {
          return `${nodes[0].fullName}${this.entity.name ? `/${this.entity.name}` : ''}`
        }
        return this.entity.name
      }
    },
    methods: {
      create,
      load,
      save,
      update,
      async initEntity(id) {
        const res = await getTree()
        this.options = Object.freeze(res.data.data)
        this.entity = await this.loadEntity(id)
      },
      async onInputParent(val) {
        if (val === this.entity.id) {
          const parentId = this.entity.parentId
          this.entity.parentId = -100
          await this.$nextTick()
          this.entity.parentId = parentId
          await this.$alert('不允许选择自身作为父编录号！')
        } else {
          this.entity.parentId = val
        }
      }
    }
  }
</script>
